let qiniuUtil = module.exports = {};
let qiniu = require('qiniu');
let config = require('config');
let crypto = require("crypto");
let errinfo = require('../errinfo');

let bucketName = config.qiniu.bucketName;
let url = require('url');

qiniu.conf.ACCESS_KEY = config.qiniu.AccessKey;
qiniu.conf.SECRET_KEY = config.qiniu.SecretKey;

// get download url
qiniuUtil.getDownloadUrl = function (src) {

    // delete url parameter
    let urlObj = url.parse(src);
    if (urlObj.search) {
        delete urlObj.search;
    }

    if (urlObj.query) {
        delete urlObj.query;
    }

    let tmpUrl = url.format(urlObj);

    //构建私有空间的链接
    let policy = new qiniu.rs.GetPolicy();
    //生成下载链接url

    return policy.makeRequest(tmpUrl);
};
// upload image
qiniuUtil.uploadImage = function (imageBuff, ext, callback) {
    /* istanbul ignore if */
    if (!imageBuff) return callback(errinfo.uploadImageBufferEmpty);
    if (!bucketName) return callback(errinfo.uploadImageBucketNameEmpty);

    /* istanbul ignore if */
    if (!ext) ext = '.jpg';
    let md5 = crypto.createHash('md5');
    md5.update(imageBuff, 'binary');
    let key = md5.digest('hex') + ext;
    let binary = new Buffer(imageBuff, 'binary');
    let putPolicy = new qiniu.rs.PutPolicy(bucketName);
    let uptoken = putPolicy.token();
    let extra = new qiniu.io.PutExtra();
    qiniu.io.put(uptoken, key, binary, extra, function (err, ret) {
        /* istanbul ignore if */
        if (err) return callback(errinfo.uploadImageQiNiuFailure);
        let url = 'http://' + config.qiniu.domain + '/' + key;
        return callback(null, url);
    });
};